Imports Microsoft.VisualBasic

' Implements ITemplate interface for new columns
Public Class GridViewTemplate
    Implements ITemplate        'ToDo: Add Implements Clauses for implementation methods of these interface(s)

    Private _templateType As ListItemType
    Private _columnName As String
    Private _col As String
    Private _dataType As String
    Private _isLabel As Boolean


    Public Sub New(ByVal type As ListItemType, ByVal colname As String, ByVal col As String, ByVal DataType As String, ByVal isLabel As Boolean)
        _templateType = type
        _columnName = colname
        _dataType = DataType
        _col = col
        _isLabel = isLabel
    End Sub 'New

    ' Databind an edit box in the grid
    Sub edt_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
        Dim txtdata As TextBox = CType(sender, TextBox)
        Dim container As GridViewRow = CType(txtdata.NamingContainer, GridViewRow)
        Dim dataValue As Object = DataBinder.Eval(container.DataItem, _columnName)
        ' Add JavaScript function sav(row,col,hours) which will save changes
        txtdata.Attributes.Add("onchange", "sav(" + container.RowIndex.ToString() + "," + _columnName + ",this.value)")
        If Not dataValue Is DBNull.Value Then
            txtdata.Text = dataValue.ToString()
        End If
    End Sub 'edt_DataBinding

    ' Databind a label 
    Sub lbl_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
        Dim lbl As Label = CType(sender, Label)
        Dim container As GridViewRow = CType(lbl.NamingContainer, GridViewRow)
        Dim dataValue As Object = DataBinder.Eval(container.DataItem, _columnName)
        If Not dataValue Is DBNull.Value Then
            lbl.Text = dataValue.ToString()
        End If
    End Sub 'lbl_DataBinding

    Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
        Dim lbl As New Label()
        Select Case _templateType
            Case ListItemType.Header
                container.Controls.Add(lbl)
                lbl.Text = _columnName

            Case ListItemType.Item
                If _isLabel Then
                    AddHandler lbl.DataBinding, AddressOf lbl_DataBinding
                    container.Controls.Add(lbl)
                Else
                    Dim edt As New TextBox()
                    edt.ID = "edt" + _col
                    container.Controls.Add(edt)
                    AddHandler edt.DataBinding, AddressOf edt_DataBinding
                    edt.Columns = 1
                End If
        End Select
    End Sub

End Class 'GridViewTemplate
